﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace AIniciacao.Lib.Sprites
{
    public class Animation
    {
        public Texture2D Texture;
        public int FramesPerSecond;
        private float timePerFrame;
        private float TotalElapsedTime;
        public Point FrameSize;
        public Point CurrentFrame;
        public Point SheetSize;
        public Point initialPosition;
        public bool isLoop;

        public Animation(Texture2D texture, int FramesPerSecond,
            int Colunas, int Linhas, int LarguraFrame, int AlturaFrame,
            Point initialPosition, bool isLoop)
        {
            this.Texture = texture;
            this.FramesPerSecond = FramesPerSecond;

            this.timePerFrame = 1 / (float)FramesPerSecond;

            this.SheetSize = new Point(Colunas, Linhas);
            this.FrameSize = new Point(LarguraFrame, AlturaFrame);

            this.CurrentFrame = new Point(0, 0);

            this.isLoop = isLoop;

            this.initialPosition = initialPosition;
        }

        public void Update(GameTime gameTime)
        {
            TotalElapsedTime +=
                (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (TotalElapsedTime > timePerFrame)
            {
                CurrentFrame.X++;
                if (CurrentFrame.X >= SheetSize.X)
                {
                    if (isLoop)
                    {
                        CurrentFrame.X = 0;
                    }
                    else
                    {
                        CurrentFrame.X--;
                    }
                }
                CurrentFrame.Y++;
                if (CurrentFrame.Y >= SheetSize.Y)
                {
                    if (isLoop)
                    {
                        CurrentFrame.Y = 0;
                    }
                    else
                    {
                        CurrentFrame.Y--;
                    }
                }

                TotalElapsedTime = 0;

            }

        }

        public void Draw( SpriteBatch spriteBatch, Vector2 position)
        {
            spriteBatch.Draw(Texture, position,
                new Rectangle(initialPosition.X + (CurrentFrame.X * FrameSize.X),
                    initialPosition.Y + (CurrentFrame.Y * FrameSize.Y),
                    FrameSize.X, FrameSize.Y),
                    Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
        }
    }
}